<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        * {
            padding: 0;
            margin: 0;
        }

        .box {
            width: 100px;
            height: 100px;
            background-color: #6ff;
            position: absolute;
            left: 0;
            top: 0;
        }
    </style>
</head>

<body>
    <div class="box">

    </div>
</body>
<script>
    var box = document.querySelector(".box");
    // document.onkeydown = function (e) {
    //     var e = e || window.event;
    //     // console.log(e);
    //     var keyCode = e.keyCode || e.which;
    //     // console.log(keyCode);

    //     if (keyCode == 37) {//左
    //         box.style.left = box.offsetLeft - 100 + "px";
    //     } else if (keyCode == 38) {//上
    //         box.style.top = box.offsetTop - 100 + "px";
    //     } else if (keyCode == 39) {//右
    //         box.style.left = box.offsetLeft + 100 + "px";
    //     } else if (keyCode == 40) {//下
    //         box.style.top = box.offsetTop + 100 + "px";
    //     }

    // }

    var timer = null;

    // timer = setInterval(function () {
    document.onkeydown = function (e) {
        var e = e || window.event;
        // console.log(e);
        var keyCode = e.keyCode || e.which;
        console.log(keyCode);

        if (keyCode == 37) {//左
            box.style.left = box.offsetLeft - 10 + "px";
        } else if (keyCode == 38) {//上
            box.style.top = box.offsetTop - 10 + "px";
        } else if (keyCode == 39) {//右
            box.style.left = box.offsetLeft + 10 + "px";
        } else if (keyCode == 40) {//下
            box.style.top = box.offsetTop + 10 + "px";
        }

    }

    // }, 100)
    // document.onkeyup = function () {
    //     clearInterval(timer);
    // }

</script>

</html>